package com.qxf.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.qxf.model.ReturnEvent;
import com.qxf.model.beans.UserSession;
import com.qxf.service.actions.AdpositionMgtAction;
import com.qxf.service.actions.LoginAction;
import com.qxf.service.actions.StatisticsAction;
import com.qxf.service.actions.UserInfoAction;
import com.qxf.util.Constants;

public class Service extends HttpServlet {

	private static final long serialVersionUID = 712928890249695026L;
	
	Logger log = Logger.getLogger(this.getClass());

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		BaseAction action = null;
		ReturnEvent ret = new ReturnEvent();
		String s = req.getParameter("s");
		log.info("service name=" + s);
		if("login".equals(s)) {
			action = new LoginAction();
		} else if(checkLoginStatus(req.getSession())) {
			if("adpmgt".equals(s)) {
				action = new AdpositionMgtAction();
			} else if("statistics".equals(s)) {
				action = new StatisticsAction();
			} else if("userinfo".equals(s)) {
				action = new UserInfoAction();
			}
		} else {
			resp.sendRedirect("index.jsp");
		}
		action.setSession(req.getSession());
		action.setUserSession((UserSession)req.getSession().getAttribute(Constants.SESSION_KEY));
		if(null != action) {
			ret = action.process(req, resp);
		}
		resp.getWriter().write(ret.toJSONString());
	}
	
	private boolean checkLoginStatus(HttpSession session) {
		UserSession userInfo = (UserSession)session.getAttribute(Constants.SESSION_KEY);
		if(null != userInfo) {
			return userInfo.isLogin();
		}
		return false;
	}
	
}
